package org.dromara.kitchen.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.kitchen.domain.BdCity;
import org.dromara.kitchen.domain.BdDistrict;
import org.dromara.kitchen.domain.dto.AreaTreeSelect;
import org.dromara.kitchen.mapper.BdCityMapper;
import org.dromara.kitchen.mapper.BdDistrictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.dromara.kitchen.domain.BdProvince;
import org.dromara.kitchen.mapper.BdProvinceMapper;
import org.dromara.kitchen.service.IBdProvinceService;

import java.util.ArrayList;
import java.util.List;

/**
 * 全国的 省份Service业务层处理
 *
 * @author Mr.Zhou
 * @date 2024-12-04
 */
@RequiredArgsConstructor
@Service
public class BdProvinceServiceImpl extends ServiceImpl<BdProvinceMapper, BdProvince> implements IBdProvinceService {

    private final BdProvinceMapper provinceMapper;
    private final BdCityMapper cityMapper;
    private final BdDistrictMapper districtMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<AreaTreeSelect> getAllArea(BdProvince province){
        List<AreaTreeSelect> list = new ArrayList<>();
        String key =  "areaList_" +province.getId();
        String keyAll = "areaAllList";
        if(province.getIsHasDis() == 0){
            key =  "areaCityList_" + province.getId();
        }
        int isHasDis = province.getIsHasDis();
        if(province.getId()!=null && province.getId() > 0){//只取当前省份的
            boolean blHasKey = redisTemplate.opsForHash().hasKey(key,key);
            if (blHasKey) {
                Object object = redisTemplate.opsForHash().get(key, key);
                String itemDicts = object != null ? object.toString() : "";
                if (!StrUtil.isBlank(itemDicts)) {
                    JSONArray jsonArray = JSONUtil.parseArray(itemDicts);
                    list = JSONUtil.toList(jsonArray.toString(), AreaTreeSelect.class);
                } else {
                    list = getAllAreaTreeList(province.getId(),isHasDis);
                    redisTemplate.opsForHash().put(key , key, JSONUtil.toJsonStr(list));
                }
            } else {
                list = getAllAreaTreeList(province.getId(),isHasDis);
                redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(list));
            }
        }else{//取所有省份的
            boolean blHasKey = redisTemplate.opsForHash().hasKey(keyAll,keyAll);
            if (blHasKey) {
                Object object = redisTemplate.opsForHash().get(keyAll, keyAll);
                String itemDicts = object != null ? object.toString() : "";
                if (!StrUtil.isBlank(itemDicts)) {
                    JSONArray jsonArray = JSONUtil.parseArray(itemDicts);
                    list = JSONUtil.toList(jsonArray.toString(), AreaTreeSelect.class);
                } else {
                    list = getAllAreaTreeList(null,isHasDis);
                    redisTemplate.opsForHash().put(keyAll, keyAll, JSONUtil.toJsonStr(list));
                }
            } else {
                list = getAllAreaTreeList(null,isHasDis);
                redisTemplate.opsForHash().put(keyAll, keyAll, JSONUtil.toJsonStr(list));
            }
        }
        return list;
    }

    @Override
    public String getAreaNameByAreaId(Integer provId, Integer cityId, Integer districtId) {
        String name = "";
        if(provId != null){
            BdProvince province = provinceMapper.selectById(provId);
            if(province != null){
                name += province.getProvinceName();
            }
        }
        if(cityId != null){
            BdCity city = cityMapper.selectById(cityId);
            if(city != null){
                name +=  " " +  city.getCityName();
            }
        }
        if(districtId != null){
            BdDistrict district = districtMapper.selectById(districtId);
            if(district != null){
                name +=  " " + district.getDistrictName();
            }
        }
        return name;
    }

    private List<AreaTreeSelect> getAllAreaTreeList(Integer provinceId,int isHasDis){
        List<AreaTreeSelect> list = new ArrayList<>();
        List<BdProvince> listProvince = new ArrayList<>();
        if(provinceId!=null){
            QueryWrapper<BdProvince> qw = new QueryWrapper<>();
            qw.eq("id",provinceId);
            listProvince = provinceMapper.selectList(qw);
        }else{
            listProvince = provinceMapper.selectList();
        }
        if(CollUtil.isNotEmpty(listProvince)){
            for (BdProvince province : listProvince){

                AreaTreeSelect provinceTree = new AreaTreeSelect();
                provinceTree.setValue(province.getId().toString());
                provinceTree.setLabel(province.getProvinceName());

                List<AreaTreeSelect> cityChilds = new ArrayList<>();


                QueryWrapper<BdCity> qw = new QueryWrapper<>();
                qw.eq("province_id",province.getId());
                List<BdCity> cities = cityMapper.selectList(qw);
                if(CollUtil.isNotEmpty(listProvince)){
                    for (BdCity city : cities){
                        AreaTreeSelect cityTree = new AreaTreeSelect();
                        cityTree.setValue(city.getId().toString());
                        cityTree.setLabel(city.getCityName());
                        cityChilds.add(cityTree);

                        if(isHasDis == 1){
                            List<AreaTreeSelect> districtChilds = new ArrayList<>();

                            QueryWrapper<BdDistrict> qwDis = new QueryWrapper<>();
                            qwDis.eq("city_id",city.getId());
                            List<BdDistrict> districts = districtMapper.selectList(qwDis);
                            if(CollUtil.isNotEmpty(districts)){
                                for (BdDistrict district : districts){
                                    AreaTreeSelect districtTree = new AreaTreeSelect();
                                    districtTree.setValue(district.getId().toString());
                                    districtTree.setLabel(district.getDistrictName());
                                    districtChilds.add(districtTree);

                                }
                            }
                            cityTree.setChildren(districtChilds);
                        }
                    }
                }
                provinceTree.setChildren(cityChilds);
                list.add(provinceTree);
            }
        }

        return list;
    }

}
